﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using StockModel;

namespace Plugins.Historical
{
	public class DataLoader
	{
		#region Attributes

		private ExchangeMarket _market;

		private readonly QuotationDataSource _quotationDataSource;
		private readonly RawStockDataSource _rawStockDataSource;
		private readonly FakeOrderExecutor _fakeOrderExecutor;

		#endregion

		#region Properties

		public ObservableCollection<Quotation> Data { get; private set; }

		#endregion

		#region Events

		public event EventHandler LastQuotation;

		#endregion

		#region Public Methods

		public DataLoader(QuotationDataSource quotationDataSource, RawStockDataSource rawStockDataSource, FakeOrderExecutor fakeOrderExecutor)
		{
			this.Data = new ObservableCollection<Quotation>();

			_quotationDataSource = quotationDataSource;
			_rawStockDataSource = rawStockDataSource;
			_fakeOrderExecutor = fakeOrderExecutor;
		}

		public void Load(DateTime date, Stock stock)
		{
			_market = _rawStockDataSource.GetMarket(stock, date);

			List<Quotation> quotations = new List<Quotation>(_quotationDataSource.GetQuotations(stock, date, _market));

			for (int index = 0; index < quotations.Count; index++)
			{
				if (index == quotations.Count - 1)
				{
					this.OnLastQuotation();
				}
				else
				{
					_fakeOrderExecutor.NextQuotation = quotations[index + 1];	
				}
				
				this.Data.Add(quotations[index]);
			}
		}

		protected virtual void OnLastQuotation()
		{
			if (this.LastQuotation != null)
			{
				this.LastQuotation(this, EventArgs.Empty);
			}
		}

		#endregion
	}
}
